<template>
  <div :class="['wx_voice',voiceActive?'playing':'']" @click="openRecording(obj.fileUrl)">
    <i :class="['fa','fa-fw','fa-volume-up',voiceActive?'flash':'']"></i>
    <!-- {{JSON.stringify(obj,null,2)}} -->
  </div>
</template>

<script>
import BenzAMRRecorder from 'benz-amr-recorder';

export default {
  props:{
    isMe:{
      type:Boolean,
      default:function(){
        return false;
      }
    },//本组件中无用,与其他组件保持格式相同用
    allowPlay:{
      type:Boolean,
      default:function(){
        return false;
      }
    },
    obj:{
      media_id:String,//临时素材库Id
      fileUrl:String,//存储在七牛的URL
      format:String,
    }
  },
  data(){
    return {
      msgtype:'voice',
      playRec: null, //播放对象
      voiceActive:null
    }
  },
  methods:{
    openRecording(_url) {
      let thisVue = this
      if ( thisVue.playRec !== null) {
        thisVue.stopPlayVoice()
      }
      thisVue.playRec = new BenzAMRRecorder()
      //⚠️注意跨域问题
      thisVue.playRec.initWithUrl( _url ).then(function() {
        thisVue.voiceActive = true
        thisVue.playRec.play()
        thisVue.playRec.onEnded(function() {
          thisVue.voiceActive = null
        })
      }).catch((e) => {
        thisVue.$message.error('播放录音失败')
      })
    },
    //停止播放
    stopPlayVoice() {
      if (this.playRec.isPlaying()) {
        this.playRec.stop()
      }
    },
  },
  mounted(){
    // console.log(`视频组件收到的allowPlay值为${this.allowPlay}`)
  },
}
</script>

<style lang="less" scoped>
.wx_voice{
  position: relative;
  display: inline-block;
  line-height:40px;
  height:40px;width:100px;
  padding:0 10px;
  border-radius: 2px;
  background-color:#95ec69;
  cursor: pointer;
  &.playing{
    cursor: not-allowed;
  }
}

@keyframes flash {
  0% { opacity: 0 }
  25% { opacity: 0.3 }
  75% { opacity: 0.7 }
  100% { opacity: 1 }
}
.flash{
  animation: flash 0.7s infinite;
}

</style>